package com.yingsheng.bi.hks.template.processor;

import com.yingsheng.bi.hks.template.events.AdviceEvent;
import com.yingsheng.bi.hks.template.events.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class Processors implements Processor {

    protected Logger log = LoggerFactory.getLogger(Processors.class);

    private int order;

    private List<Processor> processors;

    public List<Processor> getProcessors() {
        return processors;
    }

    public void setProcessors(List<Processor> processors) {
        this.processors = processors;
    }

    public void addProcessor(Processor processor) {
        if (this.processors == null) {
            this.processors = new ArrayList<>();
        }
        this.processors.add(processor);
    }

    @Override
    public void exec(Event event) {
        List<Processor> processors = getProcessors();
        if (!CollectionUtils.isEmpty(processors)) {
            if (event instanceof AdviceEvent) {
                AdviceEvent adviceEvent = (AdviceEvent) event;
                Object input = adviceEvent.getInput();
                for (Processor processor : processors) {
                    processor.exec(event);
                    adviceEvent.setInput(input);
                }
            } else {
                for (Processor processor : processors) {
                    processor.exec(event);
                }
            }
        }
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

}
